package org.seanye.erp.view.actions;

import java.io.File;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
import org.seanye.erp.view.editor.WeekEditor;
import org.seanye.erp.view.editor.WeekFileInput;

public class OpenFileAction extends Action implements IWorkbenchAction {
    private IWorkbenchWindow window;

    public OpenFileAction(IWorkbenchWindow window) {
	this.window = window;
	setText("Open File@Ctrl+O");
    }

    public static IWorkbenchAction create(IWorkbenchWindow window) {
	return new OpenFileAction(window);
    }

    @Override
    public void run() {
	FileDialog dialog = new FileDialog(window.getShell(), SWT.OPEN);
	dialog.setFilterExtensions(new String[] { "*.csv" });
	String path = dialog.open();
	if (path == null) {
	    return;
	} else {
	    try {
		PlatformUI.getWorkbench().getActiveWorkbenchWindow()
			.getActivePage().openEditor(
				new WeekFileInput(new File(path)),
				WeekEditor.ID, true);
	    } catch (PartInitException e) {
		MessageDialog.openError(window.getShell(), "Open", "Open "
			+ path + " failed.");
	    }
	}
    }

    public void dispose() {
	// Do nothing
    }
}
